package com.service.lotterySystem.service.impl;

import com.alibaba.excel.EasyExcel;
import com.service.config.utils.*;
import com.service.lotterySystem.dao.ActivityInfoDao;
import com.service.lotterySystem.dao.JoinInfoDao;
import com.service.lotterySystem.dao.PrizeInfoDao;
import com.service.lotterySystem.dao.UserInfoDao;
import com.service.lotterySystem.dto.*;
import com.service.lotterySystem.entity.ActivityInfo;
import com.service.lotterySystem.entity.JoinInfo;
import com.service.lotterySystem.entity.UserInfo;
import com.service.lotterySystem.service.ActivityService;
import com.service.lotterySystem.service.JoinInfoService;
import com.service.lotterySystem.service.PrizeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.service.config.constant.Constant.PARAMETER_NOT_FOUND;

/**
 * @author ：hjl
 * @date ：Created in 2022/01/11 19:22
 * @description：
 */
@Service
@Slf4j
public class JoinInfoServiceImpl implements JoinInfoService {
    @Resource
    private JoinInfoDao joinDao;
    @Resource
    private ActivityService activityService;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private PrizeService prizeService;
    @Resource
    private PrizeInfoDao prizeInfoDao;
    @Resource
    private ActivityInfoDao activityDao;

    private final Integer PAGE_SIZE = 10;

    @Value("${spring.filePath}")
    String filePath;
    @Value("${spring.fileUrl}")
    String fileUrl;

    /**
     * 用户参加活动
     * @param userDto
     * @param aId
     * @return
     */
    @Override
    public Result joinActivity(UserDto userDto, String aId) {
        //判断是否已经参加此活动
        ActivityInfo activityInfo = activityDao.queryById(aId);
        if (activityInfo.getAType() != 1) {
            return Result.failure("该活动已结束或还未开始，无法参加");
        }
        if (!activityInfo.getAStatus() ||activityInfo.getIsCurrent().equals("0") ) {
            return Result.failure("该活动已结束，无法参加");
        }
        boolean join = isJoin(aId, userDto.getId());
        if (join)
        {
            return Result.failure(PARAMETER_NOT_FOUND,"该用户已报名该活动，无法重复报名");
        }
        JoinInfo joinInfo = new JoinInfo();
        joinInfo.setId(IdUtil.getStringId());
        joinInfo.setJNum(getPrizeNum());
        joinInfo.setShareCount(1); //参加活动至少有一个元宝
        joinInfo.setJAddTime(new Date());
        joinInfo.setIsStatus(false);
        joinInfo.setAId(aId);
        joinInfo.setUId(userDto.getId());
        joinInfo.setIsCount(false);
        joinInfo.setJUpdateTime(new Date());
        joinInfo.setUName(userDto.getNickName());
        joinDao.insert(joinInfo);
        return Result.ok();
    }

    /**
     * 用户退出活动
     * @param userId
     * @param aid
     * @return
     */
    @Override
    public Result deleteById(String userId, String aid) {
        boolean join = isJoin(aid, userId);
        if (!join)
        {
            return Result.failure(PARAMETER_NOT_FOUND,"该用户未报名该活动，无法退出");
        }
        joinDao.deleteById1(userId,aid);
        return Result.ok();
    }

    /**
     * 用户查询参加的所有活动以及我是否中奖
     * @param userDto
     * @return
     */
    @Override
    public Result queryUserActivities(UserDto userDto,Integer type) {
        List<JoinInfo> joinInfos = joinDao.queryUsersByAid("", userDto.getId());
        List<QueryActivityInfoDto> activityDtos = activityService.queryActivitiesByUid(userDto.getId());
        List<JoinAndActivityInfoDto> joinAndActivityInfoDtos = ModelMapperUtil.strictMapList(joinInfos, JoinAndActivityInfoDto.class);
        joinAndActivityInfoDtos.forEach(joinAndActivityInfoDto -> {
            List<QueryActivityInfoDto> collect = activityDtos.stream().filter(queryActivityInfoDto -> queryActivityInfoDto.getId().equals(joinAndActivityInfoDto.getAId())).collect(Collectors.toList());
            joinAndActivityInfoDto.setAName(collect.get(0).getAName());
            joinAndActivityInfoDto.setAType(collect.get(0).getAType());
        });
        if (type != null) {
            joinAndActivityInfoDtos = joinAndActivityInfoDtos.stream().filter(joinAndActivityInfoDto -> joinAndActivityInfoDto.getAType().equals(type)).collect(Collectors.toList()); // 过滤数据
        }
        return Result.ok().setData(joinAndActivityInfoDtos);
    }

    /**
     * 查询活动参加的所有用户以及助力排名信息
     * @param aid
     * @return
     */
    @Override
    public Result queryUsersOfActivity(String aid,Boolean isMe,String cloudAuthToken) {
        Map map = new HashMap();
        List<JoinInfo> joinInfos = joinDao.queryUsersByAid(aid, "");
        List<JoinInfoDto> joinInfoDtos = ModelMapperUtil.strictMapList(joinInfos, JoinInfoDto.class);
        List<UserInfo> userInfos = userInfoDao.queryUsersOfActivity(aid);
        if (null != userInfos && userInfos.size() > 0)
        {
            joinInfoDtos.stream().forEach(joinInfoDto -> {
                List<UserInfo> collect = userInfos.stream().filter(userInfo -> userInfo.getId().equals(joinInfoDto.getUId())).collect(Collectors.toList());
                if (collect.size() > 0) {
                    String Uname = StringUtils.getStarString(collect.get(0).getTelphone(),3, 7);
                    joinInfoDto.setTelphone(Uname);
                    joinInfoDto.setUName(collect.get(0).getNickName());
                }
            });
        }
        if (isMe) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            List<JoinInfoDto> collect = joinInfoDtos.stream().filter(joinInfoDto -> joinInfoDto.getUId().equals(userId)).collect(Collectors.toList()); //排序
            List<JoinInfoDto> collect1 = joinInfoDtos.stream().filter(joinInfoDto -> !joinInfoDto.getUId().equals(userId)).collect(Collectors.toList());//排序
            collect1 = joinInfoDtos.stream().sorted(Comparator.comparing(JoinInfoDto::getShareCount).reversed()).collect(Collectors.toList()); //排序
            map.put("isMe",collect);
            map.put("isOther",collect1);
            return Result.ok().setData(map);
        }
        List<JoinInfoDto> collect = joinInfoDtos.stream().sorted(Comparator.comparing(JoinInfoDto::getShareCount).reversed()).collect(Collectors.toList()); //排序
        map.put("isMe",new ArrayList<>());
        map.put("isOther",collect);
        return Result.ok().setData(collect);
    }

    /**
     * 导出活动参加用户清单
     * @param aid
     * @return
     */
    @Override
    public Result exportJoinUsers(String aid) {
        List<JoinInfo> joinInfos = joinDao.queryUsersByAid(aid, "");
        List<JoinInfoDto> joinInfoDtos = ModelMapperUtil.strictMapList(joinInfos, JoinInfoDto.class);
        List<UserInfo> userInfos = userInfoDao.queryUsersOfActivity(aid);
        if (null != userInfos && userInfos.size() > 0)
        {
            joinInfoDtos.stream().forEach(joinInfoDto -> {
                List<UserInfo> collect = userInfos.stream().filter(userInfo -> userInfo.getId().equals(joinInfoDto.getUId())).collect(Collectors.toList());
                if (collect.size() > 0) {
                    joinInfoDto.setTelphone(collect.get(0).getTelphone());
                    joinInfoDto.setUName(collect.get(0).getNickName());
                }
            });
        }
        //排序
        List<JoinInfoDto> collect = joinInfoDtos.stream().sorted(Comparator.comparing(JoinInfoDto::getShareCount).reversed()).collect(Collectors.toList());

        List<ExportJoinUserDto> exportJoinUserDtos = ModelMapperUtil.strictMapList(collect, ExportJoinUserDto.class);

        long millis = System.currentTimeMillis();
        EasyExcel.write(filePath+"活动参加用户清单"+millis+".xlsx", ExportJoinUserDto.class).sheet().doWrite(exportJoinUserDtos);
        return Result.ok().setData(fileUrl+"活动参加用户清单"+millis+".xlsx");
    }

    /**
     * 查询用户是否已经参加某活动
     * @param aid
     * @param userId
     * @return
     */
    @Override
    public boolean isJoin(String aid,String userId){
        List<JoinInfo> joinInfos = joinDao.queryUsersByAid(aid, userId);
        if (joinInfos == null || joinInfos.size()<=0)
        {
            return false;
        }
        return true;
    }

    /**
     * 生成01 02 03 04 05 06 07格式的中奖号码
     * @return
     */
    public String getPrizeNum()
    {
        String prizeNum = Arrays.toString(DoubleBallUtil.chooseNumsByMachine());
        String prizeNum2 = prizeNum.substring(1, prizeNum.length() - 1);
        String prizeNum3 = prizeNum2.replaceAll(",", "");
        return prizeNum3;
    }
}
